<template>
  <div class="h-full flex flex-col">
    <page-header title="销售"> </page-header>
    <div class="mt-[16px]"></div>
    <n-card class="p-4 h-full" content-style="padding: 0">
      <n-grid x-gap="10" :cols="24">
        <!-- 操作台 -->
        <n-gi :span="14">
          <!-- 搜索 -->
          <div>
            <SaleSearchProduct
              v-model:value="searchKeyword"
              @pick-variant="handlePickVariant"
              @pick-sn="handlePickSNBySearch"
              showImeiTag
            />
          </div>
          <div class="mt-2"></div>
          <n-scrollbar :style="scrollContainerStyle">
            <QuickItem type="sales" @select="handlClickQuickItem" />
          </n-scrollbar>
        </n-gi>
        <!-- Cart -->
        <n-gi :span="10" class="flex flex-col flex-1">
          <div class="flex items-center">
            <n-select
              placeholder="请选择客户"
              :loading="customerSearchLoading"
              remote
              clearable
              filterable
              :options="customersList"
              value-field="id"
              label-field="name"
              @search="handleSearchCustomer"
              @update:value="handleChangeCurrentCustomer"
              v-model:value="currentCustomerId"
            >
            </n-select>
            <n-button quaternary circle class="ml-2">
              <template #icon>
                <n-icon><PersonAdd /></n-icon>
              </template>
            </n-button>
            <n-button quaternary circle class="ml-2">
              <template #icon>
                <n-icon><CreateOutline /></n-icon>
              </template>
            </n-button>
          </div>
          <div class="mt-2"></div>
          <n-scrollbar :style="cartScrollContainerStyle">
            <template v-if="salesCartList.length">
              <div class="sales-cart-list">
                <n-form size="small">
                  <n-space vertical>
                    <div
                      class="sales-cart-list__item"
                      v-for="cartItem in salesCartList"
                      :key="cartItem.uuid"
                      @click.stop="handleClickExpend(cartItem)"
                    >
                      <div class="product-name">
                        <span>{{ cartItem.name }}</span>
                        <n-popconfirm
                          @positive-click="handleRemoveCartItem(cartItem)"
                        >
                          <template #trigger>
                            <n-button quaternary circle type="primary">
                              <template #icon>
                                <n-icon><Trash /></n-icon>
                              </template>
                            </n-button>
                          </template>
                          确定要移除吗？
                        </n-popconfirm>
                      </div>
                      <n-grid :cols="24" x-gap="10">
                        <template v-if="cartItem.expand">
                          <n-gi :span="12">
                            <n-form-item label="数量">
                              <n-input-number
                                class="flex-1"
                                v-model:value="cartItem.qty"
                                :min="1"
                                @update:value="
                                (_:any) => handleUpdateQty(cartItem)
                              "
                              />
                            </n-form-item>
                          </n-gi>
                          <n-gi :span="12">
                            <n-form-item label="单价">
                              <n-input v-model:value="cartItem.soldPrice" />
                            </n-form-item>
                          </n-gi>
                          <template v-if="cartItem.hasSerialNumber === '1'">
                            <n-gi
                              :span="24"
                              v-for="(imeiItem, $index) in cartItem.imeiList"
                              :key="imeiItem.uuid"
                            >
                              <n-form-item :label="`序列号${$index + 1}`">
                                <n-input
                                  readonly
                                  clearable
                                  v-model:value="imeiItem.imei"
                                  @click.stop="
                                    handleFocusImei(imeiItem, cartItem.imeiList)
                                  "
                                />
                              </n-form-item>
                            </n-gi>
                          </template>
                        </template>
                        <template v-else>
                          <n-gi :span="12">数量: {{ cartItem.qty }}</n-gi>
                          <n-gi :span="12">单价: {{ cartItem.soldPrice }}</n-gi>
                        </template>
                      </n-grid>
                    </div>
                  </n-space>
                </n-form>
              </div>
            </template>
            <n-empty
              v-else
              class="mt-[20vh]"
              size="large"
              description="请选择商品"
            >
            </n-empty>
          </n-scrollbar>
          <div class="mt-2"></div>
          <div>
            <div class="mb-1 flex justify-between">
              <div>
                <n-button text> 添加备注 </n-button>
              </div>
              <div>
                总成交价: <span>{{ currencyFormat(totalPrice) }}</span>
              </div>
            </div>
            <div class="flex justify-between">
              <n-button secondary @click.stop="discardCartItem"
                >清空购物车</n-button
              >
              <n-button type="primary" @click.stop="handleSubmit"
                >确认</n-button
              >
            </div>
          </div>
        </n-gi>
      </n-grid>
    </n-card>

    <!-- 选择支付方式弹窗 -->
    <PaymentModal
      title="选择支付方式"
      :confirm-loading="confirmLoading"
      v-model:show="showPayment"
      :payment-methods="paymentMethods"
      :total-price="totalPrice"
      @cancel="handleHidePayment"
      @close="handleHidePayment"
      @confirm="handleClickConfirm"
    />
    <!-- 选择SN弹窗 -->
    <SaleSnModal
      v-model:show="showSaleSnModal"
      title="选择序列号"
      :variant-id="currentVariantId"
      :selectedSnId="selectedSnId"
      @pick="handlePickSN"
    />
  </div>
</template>
<script setup lang="ts">
import { computed, ref } from "vue";
import { v4 as uuidv4 } from "uuid";
import { useDialog } from "naive-ui";
import { cloneDeep, debounce, get, isEmpty } from "lodash-es";
import { PersonAdd, CreateOutline, Trash } from "@vicons/ionicons5";
import { createSalesOrder } from "@/api/sales/sales.api";
import {
  SaleSnModal,
  useSaleSnModal,
} from "@/components/biz/saleSnModal/index.ts";
import SaleSearchProduct from "@/components/biz/saleSearchProduct/index.vue";
import {
  SalesSearchSnVO,
  SalesSearchVariantVO,
  SNVO,
} from "@/types/model/sales/vos/sales.vo";
import { useSearchCustomers } from "@/components/biz/customerModal/hooks";
import PaymentModal from "@/components/biz/paymentModal/index.vue";
import { usePaymentModal } from "@/components/biz/paymentModal/hooks";
import { DictStorage } from "@/storage/dict.storage";
import { currencyFormat } from "@/common/utils/currencyFormatter/index.ts";
import QuickItem from "@/components/biz/quickItem/index.vue";
import Big from "big.js";

const scrollContainerStyle = {
  flex: 1,
  minHeight: "calc(100vh - 200px)",
  maxHeight: "calc(100vh - 200px)",
};

const cartScrollContainerStyle = {
  flex: 1,
  minHeight: "calc(100vh - 278px)",
  maxHeight: "calc(100vh - 278px)",
};

const paymentMethods = DictStorage.getDictItemsByCode(
  "pos_tradein_payment_method"
);

const dialog = useDialog();

const { showSaleSnModal, toggleShowSaleSnModal } = useSaleSnModal();

const { customersList, customerSearchLoading, handleSearchCustomer } =
  useSearchCustomers();

const {
  modalShowFlag: showPayment,
  handleShowModal: handleShowPaymentModal,
  handleHideModal: handleHidePaymentModal,
} = usePaymentModal();

const currentCustomerId = ref<string | undefined>(undefined);
const currentCustomerObj = ref<any>({});
const searchKeyword = ref<string>("");

const salesCartList = ref<any[]>([]);
const confirmLoading = ref<boolean>(false);

const currentVariantId = ref<string>("");
const imeiItemUUID = ref<string>("");
const selectedSnId = ref<string[]>();

const totalPrice = computed(() => {
  let _total = new Big(0);
  salesCartList.value.forEach((item) => {
    if (item.soldPrice && item.qty) {
      const _itemTotal = new Big(item.soldPrice).times(item.qty);
      _total = _total.plus(_itemTotal);
    }
  });

  return _total.toNumber();
});

const handlClickQuickItem = debounce(function (payload) {
  const _params: SalesSearchVariantVO = {
    ...payload,
    id: payload.variantId,
    name: payload.variantName,
  };
  handlePickVariant(_params);
}, 200);

const handleChangeCurrentCustomer = (_: any, opt: any) => {
  currentCustomerObj.value = cloneDeep(opt);
};

const handleHidePayment = () => {
  if (!confirmLoading.value) {
    handleHidePaymentModal();
  }
};

const createNewImeiItem = (variantId: string, imei: string = "") => {
  return {
    checkImeiLoading: false,
    id: "",
    variantId: variantId,
    uuid: uuidv4(),
    imei: imei,
    available: -1,
    message: "",
  };
};

const handleClickExpend = (payload: any) => {
  console.log(payload);
  const variantId = get(payload, "variantId") || "";
  salesCartList.value.forEach((item) => {
    if (item.expand) {
      item.expand = false;
    }

    if (get(item, "variantId") === variantId) {
      item.expand = true;
    }
  });
};

const handlePickVariant = (payload: SalesSearchVariantVO) => {
  const variantId = get(payload, "id") || "";
  const hasSerialNumber = get(payload, "hasSerialNumber") || "";
  if (!variantId) {
    return;
  }

  let existItem: any = {};

  salesCartList.value.forEach((item) => {
    if (item.expand) {
      item.expand = false;
    }

    if (get(item, "variantId") === variantId) {
      existItem = item;
    }
  });

  if (isEmpty(existItem)) {
    const cartItem: any = {
      uuid: uuidv4(),
      variantId,
      name: payload.name,
      sku: payload.sku,
      originSoldPrice: payload.soldPrice,
      soldPrice: payload.soldPrice,
      hasSerialNumber: payload.hasSerialNumber,
      imeiList: [],
      qty: 1,
      expand: true,
    };
    if (hasSerialNumber === "1") {
      cartItem.imeiList = [createNewImeiItem(variantId)];
    }
    salesCartList.value.push(cartItem);
  } else {
    existItem.qty = existItem.qty + 1;
    if (hasSerialNumber === "1") {
      existItem.imeiList.push(createNewImeiItem(variantId));
    }
    existItem.expand = true;
  }
};

const handlePickSNBySearch = (payload: SalesSearchSnVO) => {
  const variantId = get(payload, "variantId") || "";
  const snId = get(payload, "snId") || "";
  if (!variantId || !snId) {
    return;
  }

  let existItem: any = {};

  salesCartList.value.forEach((item) => {
    if (item.expand) {
      item.expand = false;
    }

    if (get(item, "variantId") === variantId) {
      existItem = item;
    }
  });

  const newImeiItem = {
    checkImeiLoading: false,
    id: payload.snId,
    variantId,
    uuid: uuidv4(),
    imei: payload.snName,
    available: -1,
    message: "",
  };

  if (isEmpty(existItem)) {
    const cartItem: any = {
      uuid: uuidv4(),
      variantId,
      name: payload.variantName,
      sku: payload.sku,
      originSoldPrice: payload.soldPrice,
      soldPrice: payload.soldPrice,
      hasSerialNumber: payload.hasSerialNumber,
      imeiList: [newImeiItem],
      qty: 1,
      expand: true,
    };
    salesCartList.value.push(cartItem);
  } else {
    existItem.expand = true;
    if (existItem.imeiList.length) {
      const existSnIndex = existItem.imeiList.findIndex(
        (item: any) => item.id === snId
      );
      if (existSnIndex >= 0) {
        dialog.warning({
          title: "温馨提示",
          content: "当前序列号已被添加",
          positiveText: "确定",
          negativeText: "取消",
        });
        return;
      }
    }
    existItem.imeiList.push(newImeiItem);
    existItem.qty = existItem.qty + 1;
  }
};

const handleUpdateQty = debounce(function (payload: any) {
  console.log(payload);
  const { qty, imeiList, hasSerialNumber, variantId } = payload;
  if (hasSerialNumber === "1") {
    let diff = qty - imeiList.length;
    if (diff > 0) {
      let diffImeiList = [];
      for (let i = 0; i < diff; i++) {
        diffImeiList.push(createNewImeiItem(variantId));
      }
      imeiList.push(...diffImeiList);
    } else if (diff < 0) {
      // 从尾部开始删除
      for (let i = 0; i < Math.abs(diff); i++) {
        imeiList.pop();
      }
    }
  }
}, 200);

const handleFocusImei = (payload: any, imeiList: any[]) => {
  console.log(payload);
  currentVariantId.value = payload.variantId;
  imeiItemUUID.value = payload.uuid;
  let _selectedSnIds: string[] = [];
  imeiList.forEach((item) => {
    if (item.id) {
      _selectedSnIds.push(item.id);
    }
  });
  selectedSnId.value = _selectedSnIds;
  console.log(selectedSnId.value);
  toggleShowSaleSnModal(true);
};

const handleClickConfirm = debounce(async function (paymentMethods: any[]) {
  let params = {
    customerId: currentCustomerId.value as string,
    total: totalPrice.value,
    items: salesCartList.value.map((item) => {
      return {
        variantId: item.variantId,
        originPrice: item.originSoldPrice,
        unitPrice: item.soldPrice,
        quantity: item.qty,
        snIds: item.imeiList.map((imeiItem: any) => imeiItem.id),
      };
    }),
    paymentItems: paymentMethods.map((item) => {
      return {
        method: item.paymentMethod,
        amount: item.amount,
      };
    }),
  };
  console.log(params);
  createSalesOrder(params).then((res) => {
    console.log(res);
  });
}, 200);

const handleRemoveCartItem = (payload: any) => {
  salesCartList.value = salesCartList.value.filter(
    (item) => item.uuid !== payload.uuid
  );
};

const discardCartItem = () => {
  salesCartList.value = [];
};

const handleSubmit = () => {
  if (!currentCustomerId.value) {
    dialog.warning({
      title: "温馨提示",
      content: "请选择客户",
      positiveText: "确定",
      negativeText: "取消",
    });
    return;
  }

  if (!salesCartList.value.length) {
    dialog.warning({
      title: "温馨提示",
      content: "销售清单为空，请添加回收设备",
      positiveText: "确定",
      negativeText: "取消",
    });
    return;
  }

  // 检查salesCartList.value的 imeiList 是否有重复
  const hasRepeatSN = salesCartList.value.some((item) => {
    const imeiList = item.imeiList || [];
    const _imeiList = imeiList
      .map((item: any) => item.id)
      .filter((item: any) => item);
    return _imeiList.length !== new Set(_imeiList).size;
  });

  if (hasRepeatSN) {
    dialog.warning({
      title: "温馨提示",
      content: "请检查设备序列号是否重复",
      positiveText: "确定",
      negativeText: "取消",
    });
    return;
  }

  // 检查salesCartList.value的 imeiList 是否有选择
  const hasEmptySN = salesCartList.value.some((item) => {
    const imeiList = item.imeiList || [];
    return imeiList.some((item: any) => !item.id);
  });

  if (hasEmptySN) {
    dialog.warning({
      title: "温馨提示",
      content: "请检查设备序列号是否为空",
      positiveText: "确定",
      negativeText: "取消",
    });
    return;
  }

  handleShowPaymentModal();
};

const handlePickSN = (payload: any) => {
  const targetCartItem =
    salesCartList.value.find(
      (item) => item.variantId === currentVariantId.value
    ) || {};
  if (!isEmpty(targetCartItem)) {
    const targetImeiItem =
      targetCartItem.imeiList.find(
        (item: any) => item.uuid === imeiItemUUID.value
      ) || {};
    if (!isEmpty(targetImeiItem)) {
      const { id, name } = payload;
      targetImeiItem.id = id;
      targetImeiItem.imei = name;
    }
    imeiItemUUID.value = "";
    selectedSnId.value = [];
  }
};
</script>
<style lang="scss" scoped>
@import "./index.scss";
</style>
